import 'package:flutter/material.dart';
import 'package:get/get.dart';

class WorkerController extends GetxController {
  final _counter = 0.obs;
  set counter(value) => this._counter.value = value;
  get counter => this._counter.value;

  late Worker worker;
  int coinCount = 0;

  @override
  void onInit() {
    worker = interval(
      _counter,
      (_) {
        coinCount++;
        print("金币数: $coinCount");
      },
      time: Duration(seconds: 2),
      condition: () => coinCount < 10,
    );
    super.onInit();
  }

  @override
  void dispose() {
    worker.dispose();
    super.dispose();
  }
}

class WorkersDemoPage extends StatelessWidget {
  WorkersDemoPage({Key? key}) : super(key: key);
  final workerControler = WorkerController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Workder 示例'),
      ),
      body: Center(
        child: GetX<WorkerController>(
          builder: (controller) => Text('${controller.counter}'),
          init: workerControler,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          workerControler.counter++;
        },
      ),
    );
  }
}
